/* eslint-disable keyword-spacing,indent */
// +----------------------------------------------------------------------
// | CmsWing [ 网站内容管理框架 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2115 http://www.cmswing.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: arterli <arterli@qq.com>
// +----------------------------------------------------------------------

module.exports = class extends think.cmswing.admin {
  constructor(ctx) {
    super(ctx); // 调用父级的 constructor 方法，并把 ctx 传递进去
    // 其他额外的操作
    this.tactive = 'gongxufabu';
  }
  /**
   * index action
   * @return {Promise} []
   */
  indexAction() {
    // auto render template file index_index.html

    return this.display();
  }

  // 发布审核-未审核
  async listcheckAction() {
    const map = {
      status: 0
    };
    const data = await this.model('cmswing/gongxufabu').where(map).page(this.get('page') || 1, 20).order('id desc').countSelect();
    const html = this.pagination(data);
    this.assign('pagerData', html); // 分页展示使用
    this.assign('list', data.data);
    this.meta_title = '发布审核-未审核';
    return this.display();
  }
  // 发布审核-已审核
  async listcheckedAction() {
    const query = unflatten(this.get());
    const map = await getmap(this.tactive, query);
    map.check_remarks_id = ['!=', null];
    const data = await this.model('cmswing/gongxufabu').where(map).page(this.get('page') || 1, 20).order('id desc').countSelect();
    const html = this.pagination(data);
    this.assign('pagerData', html); // 分页展示使用
    this.assign('list', data.data);
    this.meta_title = '发布审核-已审核';
    return this.display();
  }
  // 发布审核-已审核导出
  async listcheckedexportAction() {
    const query = unflatten(this.get());
    const map = await getmap(this.tactive, query);
    map.check_remarks_id = ['!=', null];
    const data = await this.model('cmswing/gongxufabu').where(map).order('id desc').select();
    const pathname = get_pathname(this.referer());
    const csvdata = await json2csv(_csvconfig[pathname], data);
    this.ctx.set('Content-Type', 'application/vnd.openxmlformats;charset=utf-8');
    this.ctx.set('Content-Disposition', 'attachment; filename=' + encodeURI(get_remark_type(pathname)) + '.csv');
    this.ctx.body = csvdata;
  }
  // 发布复核-未复核
  async listreviewAction() {
    const map = {
      recipient_remarks_id: ['!=', null],
      review_remarks_id: ['=', null]
    };
    const data = await this.model('cmswing/gongxufabu').where(map).page(this.get('page') || 1, 20).order('id desc').countSelect();
    const html = this.pagination(data);
    this.assign('pagerData', html); // 分页展示使用
    this.assign('list', data.data);
    this.meta_title = '发布复核-未复核';
    return this.display();
  }
  // 发布复核-已复核
  async listreviewedAction() {
    const query = unflatten(this.get());
    const map = await getmap(this.tactive, query);
    map.review_remarks_id = ['!=', null];
    const data = await this.model('cmswing/gongxufabu').where(map).page(this.get('page') || 1, 20).order('id desc').countSelect();
    const html = this.pagination(data);
    this.assign('pagerData', html); // 分页展示使用
    this.assign('list', data.data);
    this.meta_title = '发布复核-已复核';
    return this.display();
  }
  // 发布复核-已复核导出
  async listreviewedexportAction() {
    const query = unflatten(this.get());
    const map = await getmap(this.tactive, query);
    map.status = ['!=', 2];
    map.review_remarks_id = ['!=', null];
    const data = await this.model('cmswing/gongxufabu').where(map).order('id desc').select();
    const pathname = get_pathname(this.referer());
    const csvdata = await json2csv(_csvconfig[pathname], data);
    this.ctx.set('Content-Type', 'application/vnd.openxmlformats;charset=utf-8');
    this.ctx.set('Content-Disposition', 'attachment; filename=' + encodeURI(get_remark_type(pathname)) + '.csv');
    this.ctx.body = csvdata;
  }
  // 派单管理--未派单
  async listsendAction() {
    const map = {
      status: 1,
      send_remarks_id: ['=', null]
    };
    if (!this.is_admin) {
      map.push_userid = this.user.id;
    }
    const data = await this.model('cmswing/gongxufabu').where(map).page(this.get('page') || 1, 20).order('id desc').countSelect();
    const html = this.pagination(data);
    this.assign('pagerData', html); // 分页展示使用
    this.assign('list', data.data);
    this.meta_title = '派单管理--未派单';
    return this.display();
  }
  // 派单管理--已派单
  async listsendedAction() {
    const query = unflatten(this.get());
    const map = await getmap(this.tactive, query);
    map.send_remarks_id = ['!=', null];
    if (!this.is_admin) {
      map.push_userid = this.user.id;
    }
    const data = await this.model('cmswing/gongxufabu').where(map).page(this.get('page') || 1, 20).order('id desc').countSelect();
    const html = this.pagination(data);
    this.assign('pagerData', html); // 分页展示使用
    this.assign('list', data.data);
    this.meta_title = '派单管理--已派单';
    return this.display();
  }
  // 派单管理--已派单导出
  async listsendedexportAction() {
    const query = unflatten(this.get());
    const map = await getmap(this.tactive, query);
    map.send_remarks_id = ['!=', null];
    const data = await this.model('cmswing/gongxufabu').where(map).order('id desc').select();
    const pathname = get_pathname(this.referer());
    const csvdata = await json2csv(_csvconfig[pathname], data);
    this.ctx.set('Content-Type', 'application/vnd.openxmlformats;charset=utf-8');
    this.ctx.set('Content-Disposition', 'attachment; filename=' + encodeURI(get_remark_type(pathname)) + '.csv');
    this.ctx.body = csvdata;
  }
  // 信息管理-存续信息
  async listsaleAction() {
    const query = unflatten(this.get());
    const map = await getmap(this.tactive, query);
    map.status = 5;
    const data = await this.model('cmswing/gongxufabu').where(map).page(this.get('page') || 1, 20).order('id desc').countSelect();
    const html = this.pagination(data);
    this.assign('pagerData', html); // 分页展示使用
    this.assign('list', data.data);
    this.meta_title = '信息管理-存续信息';
    return this.display();
  }
  // 信息管理-存续信息导出
  async listsaleexportAction() {
    const query = unflatten(this.get());
    const map = await getmap(this.tactive, query);
    map.status = 5;
    const data = await this.model('cmswing/gongxufabu').where(map).order('id desc').select();
    const pathname = get_pathname(this.referer());
    const csvdata = await json2csv(_csvconfig[pathname], data);
    this.ctx.set('Content-Type', 'application/vnd.openxmlformats;charset=utf-8');
    this.ctx.set('Content-Disposition', 'attachment; filename=' + encodeURI(get_remark_type(pathname)) + '.csv');
    this.ctx.body = csvdata;
  }
  // 信息管理-信息列表
  async listallAction() {
    const query = unflatten(this.get());
    const map = await getmap(this.tactive, query);
    const data = await this.model('cmswing/gongxufabu').where(map).page(this.get('page') || 1, 20).order('id desc').countSelect();
    const html = this.pagination(data);
    this.assign('pagerData', html); // 分页展示使用
    this.assign('list', data.data);
    this.meta_title = '信息管理-信息列表';
    return this.display();
  }
  // 信息管理-信息列表导出
  async listallexportAction() {
    const query = unflatten(this.get());
    const map = await getmap(this.tactive, query);
    const data = await this.model('cmswing/gongxufabu').where(map).order('id desc').select();
    const pathname = get_pathname(this.referer());
    const csvdata = await json2csv(_csvconfig[pathname], data);
    this.ctx.set('Content-Type', 'application/vnd.openxmlformats;charset=utf-8');
    this.ctx.set('Content-Disposition', 'attachment; filename=' + encodeURI(get_remark_type(pathname)) + '.csv');
    this.ctx.body = csvdata;
  }
  // 问题信息
  async listproblemAction() {
    const query = unflatten(this.get());
    const map = await getmap(this.tactive, query);
    map.status = ['in', [2, 6]];
    map.problem_type = '问题信息';
    const data = await this.model('cmswing/gongxufabu').where(map).page(this.get('page') || 1, 20).order('id desc').countSelect();
    const html = this.pagination(data);
    this.assign('pagerData', html); // 分页展示使用
    this.assign('list', data.data);
    this.meta_title = '问题信息';
    return this.display();
  }
  // 问题信息导出
  async listproblemexportAction() {
    const query = unflatten(this.get());
    const map = await getmap(this.tactive, query);
    map.status = ['in', [2, 6]];
    map.problem_type = '问题信息';
    const data = await this.model('cmswing/gongxufabu').where(map).order('id desc').select();
    const pathname = get_pathname(this.referer());
    const csvdata = await json2csv(_csvconfig[pathname], data);
    this.ctx.set('Content-Type', 'application/vnd.openxmlformats;charset=utf-8');
    this.ctx.set('Content-Disposition', 'attachment; filename=' + encodeURI(get_remark_type(pathname)) + '.csv');
    this.ctx.body = csvdata;
  }
  /**
   * 审核并分配业务内勤
   */
  async pushAction() {
    if (this.isPost) {
      const remarkData = this.post();
      const {
        id
      } = remarkData;
      const faburen = await this.model('cmswing/gongxufabu').where({
        id: id
      }).find();
      if (faburen.fabureninfo.groupid == 12) {
        return this.fail('核心企业发布的信息无法分配内勤!');
      }
      remarkData.status = 1;
      const {
        remarksId,
        updateData
      } = await this.addremark();
      updateData.check_remarks_id = remarksId;
      if (!think.isEmpty(remarksId)) {
        const res = await this.model('gongxufabu').where({
          id: id
        }).update(updateData);
        if (res) {
          return this.success({
            name: '指定业务推送人员成功！'
          });
        } else {
          return this.fail('指定业务推送人员失败！');
        }
      } else {
        return this.fail('指定业务推送人员失败！');
      }
    } else {
      const id = this.get('id');
      this.assign('id', id);
      // const companyList = await this.model('cmswing/zzjg').select();
      const userIds = await this.model('auth_user_role').where({
        role_id: ['in', [10, 11, 14]]
      }).getField('user_id');
      const users = await this.model('cmswing/member').where({
        id: ['in', userIds]
      }).select();
      const companyList = [];
      for (let index = 0; index < users.length; index++) {
        const element = users[index];
        const resIndex = companyList.findIndex((item) => {
          if(element.zzjginfo) {
            return item.id === element.zzjginfo.id;
          }else{
            return false;
          }
        });
        if (resIndex == -1) {
          if(element.zzjginfo) {
            companyList.push({
              id: element.zzjginfo.id,
              zzjg: element.zzjginfo.zzjg,
              userinfo: [{
                id: element.id,
                username: element.username,
                zzjg: element.zzjg
              }]
            });
          }
        } else {
          companyList[resIndex].userinfo.push({
            id: element.id,
            username: element.username,
            zzjg: element.zzjg
          });
        }
      }
      this.assign('companyList', companyList);
      this.meta_title = '推送';
      return this.display();
    }
  }
  /**
   * 上架
   */
  async saleAction() {
    if (this.isPost) {
      const remarkData = this.ctx.request.body.post;
      const {
        id,
        remark_type
      } = remarkData;
      remarkData.status = 5;
      const {
        remarksId,
        updateData
      } = await this.addremark(remarkData);
      const remarkKey = get_remark_key(remark_type);
      if (remarkKey) {
        updateData[remarkKey] = remarksId;
      }
      updateData.sale_time = new Date().getTime();
      if (!think.isEmpty(remarksId)) {
        const res = await this.model('gongxufabu').where({
          id: id
        }).update(updateData);
        if (res) {
          return this.success({
            name: '上架成功!'
          });
        } else {
          return this.fail('上架失败!');
        }
      } else {
        return this.fail('上架失败!');
      }
    } else {
      const id = this.get('id');
      this.assign('id', id);
      const referer = get_pathname(this.referer());
      const reasonsMap = {
        'admin/gongxufabu/listreview': ['价格过高', '货物品质差', '对方不负责送货', '对方不承担运费', '其他']
      };
      this.assign('reasons', reasonsMap[referer]);
      this.meta_title = '上架';
      return this.display();
    }
  }
  /**
   * 退回下架
   */
  async offsaleAction() {
    if (this.isPost) {
      const remarkData = this.post();
      const {
        id,
        remark_type,
        operation
      } = remarkData;
      remarkData.status = get_offsale_status(remark_type);
      const {
        remarksId,
        updateData
      } = await this.addremark();
      const remarkKey = get_remark_key(remark_type);
      if (remarkKey) {
        updateData[remarkKey] = remarksId;
      }
      if (remarkKey == 'offsale_remarks_id') updateData.offsale_time = new Date().getTime();
      updateData.decision_problem_node = get_pathname(this.referer());
      updateData.decision_problem_time = remarkData.remark_time;
      updateData.decision_problem_userid = remarkData.remark_name;
      if (!think.isEmpty(remarksId)) {
        const res = await this.model('gongxufabu').where({
          id: id
        }).update(updateData);
        if (res) {
          return this.success({
            name: operation + '成功!'
          });
        } else {
          return this.fail(operation + '失败!');
        }
      } else {
        return this.fail(operation + '失败!');
      }
    } else {
      const {
        id,
        operation
      } = this.get();
      this.assign('id', id);
      this.assign('operation', operation);
      this.assign('problem_type', ['问题信息', '其他']);
      this.meta_title = '退回';
      return this.display();
    }
  }

  /**
   * 派单给业务员
   */
  async sendAction() {
    if (this.isPost) {
      const remarkData = this.post();
      const {
        id
      } = remarkData;
      remarkData.status = 3;
      const {
        remarksId,
        updateData
      } = await this.addremark();
      updateData.send_remarks_id = remarksId;
      if (!think.isEmpty(remarksId)) {
        const res = await this.model('gongxufabu').where({
          id: id
        }).update(updateData);
        if (res) {
          return this.success({
            name: '派单成功！'
          });
        } else {
          return this.fail('派单失败！');
        }
      } else {
        return this.fail('派单失败！');
      }
    } else {
      const id = this.get('id');
      this.assign('id', id);
      const yuangong = await this.model('cmswing/member').where({
        groupid: 12,
        ygbh: ['NOTLIKE', '']
      }).select();
      const companyList = [];
      for (let index = 0; index < yuangong.length; index++) {
        const element = yuangong[index];
        const resIndex = companyList.findIndex((item) => {
          return item.gsmc === element.gsmc;
        });
        if (resIndex == -1) {
          companyList.push({
            gsmc: element.gsmc,
            nodes: [{
              id: element.id,
              real_name: element.real_name,
              mobile: element.mobile
            }]
          });
        } else {
          companyList[resIndex].nodes.push({
            id: element.id,
            real_name: element.real_name,
            mobile: element.mobile
          });
        }
      }
      this.assign('companyList', companyList);
      this.meta_title = '派单';
      return this.display();
    }
  }
  // 订单列表
  async listAction() {
    const status = this.get('status');
    const map = {};
    if (!think.isEmpty(status)) {
      map.status = status;
      this.assign('status', status);
    }
    const q = this.get('q');
    if (!think.isEmpty(q)) {
      map['shangpingleibie|diqu'] = ['like', '%' + q + '%'];
    }
    // this.config("db.nums_per_page",20)
    const data = await this.model('gongxufabu').where(map).page(this.get('page') || 1, 20).order('id desc').countSelect();
    const html = this.pagination(data);
    this.assign('pagerData', html); // 分页展示使用
    // console.log(data.data);
    this.active = 'admin/gongxufabu/list';
    this.assign('list', data.data);
    this.meta_title = '发布管理';
    return this.display();
  }

  /**
   * 审核并分配业务内勤
   */
  async auditAction() {
    if (this.isPost) {
      console.log('+++++++++');
      const id = this.post('id');
      const faburen = await this.model('gongxufabu').where({
        id: id
      }).getField('faburen', true);
      const groupid = await this.model('member').where({
        id: faburen
      }).getField('groupid', true);
      if (groupid == 12) {
        return this.fail('核心企业发布无法分配内勤！');
      }
      const company = this.post('company');
      const shenheshijian = new Date().toLocaleString();
      const res = await this.model('gongxufabu').where({
        id: id
      }).update({
        zzjg: company,
        status: 1,
        shenheshijian: shenheshijian
      });
      return this.success({
        name: '指定业务内勤组织成功！'
      });
    } else {
      const id = this.get('id');
      this.assign('id', id);
      const companyList = await this.model('zzjg').select();
      this.assign('companyList', companyList);
      this.meta_title = '内勤组织分配';
      return this.display();
    }
  }

  /**
   * 作废订单
   */
  async voidAction() {
    if (this.isPost) {
      const id = this.post('id');
      const zuofei_remark = this.post('zuofei_remark');
      const zuofeishijian = new Date().toLocaleString();
      const voids = await this.model('gongxufabu').where({
        id: id
      }).update({
        status: 6,
        zuofei_remark: zuofei_remark,
        zuofeishijian: zuofeishijian
      });
      if (voids) {
        return this.success({
          name: '操作成功！',
          url: this.referer()
        });
      } else {
        return this.fail('操作失败！');
      }
    } else {
      const id = this.get('id');
      this.assign('id', id);
      this.meta_title = '审核订单';
      return this.display();
    }
  }

  /**
   * 直接释放发布信息
   */
  async shifangAction() {
    if (this.isPost) {
      const id = this.post('id');
      const shifang_remark = this.post('shifang_remark');
      const shifangshijian = new Date().toLocaleString();
      const shifang = await this.model('gongxufabu').where({
        id: id
      }).update({
        status: 5,
        shifang_remark: shifang_remark,
        shifangshijian: shifangshijian
      });
      if (shifang) {
        return this.success({
          name: '信息释放成功！'
        });
      } else {
        return this.fail('操作失败！');
      }
    } else {
      const id = this.get('id');
      this.assign('id', id);
      this.meta_title = '释放订单';
      return this.display();
    }
  }

  /**
   * 查看订单
   * @returns {*}
   */
  async seeAction() {
    const id = this.get('id');
    this.meta_title = '查看发布详情';
    // 获取发布信息
    const gongxufabu = await this.model('cmswing/gongxufabu').find(id);
    this.assign('gongxufabu', gongxufabu);
    const url = gongxufabu.tupian ? JSON.parse(gongxufabu.tupian) : [];
    this.assign('url', url);
    this.assign('user', gongxufabu.fabureninfo);
    return this.display();
  }

  /**
   * 查看订单
   */
  vieworderAction() {
    const list = [1, 2, 3];
    this.assign('list', list);
    return this.display();
  }
};
